package com.kgc.rb.common.kafka;

import com.kgc.rb.common.configration.KafkaConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

@Component
public class KafkaTools {

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Autowired
    private KafkaConfiguration kafkaConfiguration;

    /**
     * 1.区分项目
     * 2.区分日志的等级【普通日志，错误日志】
     *   topic:项目名称-日志等级
     */

    /**
     * 发送普通的信息
     * @param message 信息的内容
     * @return
     */
    public String sendInfoMessage(String message){
        try {
            kafkaTemplate.send(kafkaConfiguration.getModuleName()+"-"+KafkaConfiguration.LogType.INFO,
                    KafkaConfiguration.qgKey,message);
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        }
        return "success";
    }

    /**
     * 发送异常信息到Kafka中
     * @param em 异常对象
     * @return
     */
    public String sendErrorMessage(Exception em){
        try {
            Writer writer = new StringWriter();
            //将上面的writer对象包装成一个PrintWriter对象
            PrintWriter pw = new PrintWriter(writer);
            //将错误的信息打印到一个printerwriter对象中
            em.printStackTrace(pw);
            kafkaTemplate.send(kafkaConfiguration.getModuleName()+"-"+KafkaConfiguration.LogType.ERROR,
                    KafkaConfiguration.qgKey,writer.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        }
        return "success";
    }
}
